#coding=UTF-8

from ctypes import *
import os

gIctclasEncoding = {
    'UNKNOWN': 0,
	'ASCII': 1,
	'GB': 2,
	'UTF-8': 3,
	'BIG5': 4
}

gMainAttrWeight = {
    'n': 10,#名词
    'v': 2,#动词
    't': 7,#时间
    'a': 1,#形容词
    's': 1,#处所
    'f': 1,#方位
    'z': 1,#状态
    'b': 1,#区别
    'r': 1,#代词
    'm': 1,#数词
    'q': 1,#量词
    'd': 1,#副词
    'p': 1,#介词
    'c': 1,#连词
    'u': 1,#助词
    'e': 1,#感叹词
    'y': 1 #语气词
}

gSubAttrWeight = {
    'r' : 10,#人名
    'r1': 2,#汉语姓氏
    'r2': 2,#汉语名字
    'rj': 10,#日语人名
    'rf': 10,#音译人名
    's' : 5,#地名
    'sf': 5,#音译地名
    't' : 10,#机构团体
    'z' : 10,#其它专名
    'l' : 10,#名词性惯用语
    'g' : 2 ,#名词性语素
}

    
class WordAttr(object):

    def __init__(self, s):
        self._mainAttr = s[0:1]
        self._subAttr = None
        
        if gMainAttrWeight.has_key(self._mainAttr):
            self._wt = gMainAttrWeight[self._mainAttr]
        else:
            self._wt = 0
            
        if len(s) > 1:
            self._subAttr = s[1:]
            if gSubAttrWeight.has_key(self._subAttr):
                self._wt = self._wt + gSubAttrWeight[self._subAttr]

    def getWeight(self):
        return self._wt
        
    def mainAttr(self):
        return self._mainAttr
    
    def subAttr(self):
        return self._subAttr
###
        
#chinese word analyzer
class Cwa(object):
    
    def __init__(self):
        libPath = '.'
        self._lib = cdll.LoadLibrary('ICTCLAS50.dll')
        self._lib.ICTCLAS_Init(c_char_p(libPath))

    def __del__(self):
        self._lib.ICTCLAS_Exit()
    
    def analyzeWord(self, txt, encoding='UTF-8'):
        cstr = c_char_p(txt.encode(encoding))
        cstrLen = len(cstr.value)
        outBuf = create_string_buffer(cstrLen*6)
        self._lib.ICTCLAS_ParagraphProcess(cstr, cstrLen, addressof(outBuf), c_int(gIctclasEncoding[encoding]))
        return outBuf.value.decode(encoding)
    
    def analyzeWordAttr(self, txt, encoding='UTF-8'):
        s = self.analyzeWord(txt, encoding)
        ss = s.split(' ')
        wordAttrs = set([])
        for e in ss:
            t = e.split('/')
            if len(t) > 1:
                wordAttrs.add(WordAttr(t[1]))
            
        return wordAttrs

    def sumWeight(self, wordAttrs):
        s = 0
        for wa in wordAttrs:
            s = s + wa.getWeight()
        return s

if __name__ == '__main__':
    cwa = Cwa()
    
    tList = [
    u'蒙提·派森的飞行马戏团', 
    u'直译式电脑编程语言', 
    u'脚本语言', 
    u'Apache', 
    u'Boost C++ Libraries', 
    u'向下兼容', 
    u'Web应用框架', 
    u'广田弘毅',
    u'王俊霖',
    u'美国'
    ]
    
    for t in tList:
        print(cwa.analyzeWord(t))
        s2 = cwa.analyzeWordAttr(t)
        print(cwa.sumWeight(s2))
    
    os.system('pause')